/**   
 *    
 * 项目名称：SmartKungFu   
 * 类名称：WenwInfoController   
 * 类描述：文章控制层   
 * 创建人：zhangl  
 * 创建时间：2016年10月17日 下午5:22:46   
 * 修改人：zhangl   
 * 修改时间：2016年10月17日 下午5:22:46   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.controller;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.github.miemiedev.mybatis.paginator.domain.Paginator;
import com.lst.common.BaseController;
import com.lst.common.CommonEnum;
import com.lst.exception.MyException;
import com.lst.model.FolPara;
import com.lst.model.MstButton;
import com.lst.model.MstUser;
import com.lst.model.Resources;
import com.lst.model.WenwInfo;
import com.lst.service.MstButtonService;
import com.lst.service.ResourcesService;
import com.lst.service.WenwInfoService;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;

/**
 * @ClassName: WenwInfoController
 * @Description: 文章控制层
 * @author zhangl
 * @date 2016年10月17日 下午5:22:46
 *
 */
@Controller
@RequestMapping("wenwInfoController")
public class WenwInfoController extends BaseController {

	@Autowired
	private MstButtonService mstButtonService;

	@Autowired
	private WenwInfoService wenwInfoService;

	@Autowired
	private ResourcesService resourcesService;

	/**
	 * 
	 * @Title: list
	 * @Description: 页面加载
	 * @param @param request
	 * @param @param response
	 * @param @param menuId
	 * @param @param page
	 * @param @param rows
	 * @param @param index_exp
	 * @param @param index_che
	 * @param @param minDate
	 * @param @param maxDate
	 * @param @param titleFol
	 * @param @param authorFol
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return ModelAndView    返回类型
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(required = true) int menuId,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGE) int page,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) int rows,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che,
			@RequestParam(required = false,defaultValue = "") String minDate,
			@RequestParam(required = false,defaultValue = "") String maxDate,
			@RequestParam(required = false,defaultValue = "") String titleFol,
			@RequestParam(required = false,defaultValue = "") String authorFol) throws MyException {
		Date startDate = new Date();
		logger.info("list begin: " + startDate);

		FolPara folPara = new FolPara();
		folPara.setMenuId(menuId);
		folPara.setPage(page);
		folPara.setRows(rows);
		folPara.setTitleFol(titleFol);
		folPara.setAuthorFol(authorFol);

		folPara.setMaxDate(maxDate);
		folPara.setMinDate(minDate);

		MstUser mstUser = this.getMySession().getMstUser();
		List<MstButton> btns = CommonUtils.readPermissionWithBtn(menuId, mstUser, mstButtonService);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_KUNGFU + "wenw_list");
		mv.addObject("btns", btns);
		mv.addObject("folPara",folPara);

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("list end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	 * @Title: queryList
	 * @Description:获取结果集
	 * @param @param page
	 * @param @param pageSize
	 * @param @param sort
	 * @param @param order
	 * @param @param title
	 * @param @param author
	 * @param @param minDate
	 * @param @param maxDate
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return Object    返回类型
	 */
	@RequestMapping(value = "/queryList")
	@ResponseBody
	public Object queryList(
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGE) Integer page,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) Integer pageSize,
			@RequestParam(required = false,defaultValue = "")String sort,
			@RequestParam(required = false,defaultValue = CommonEnum.SYSTEM_ORDER_DESC)String order,
			@RequestParam(required = false,defaultValue = "")String title,
			@RequestParam(required = false,defaultValue = "")String author,
			@RequestParam(required = false,defaultValue = "") String minDate,
			@RequestParam(required = false,defaultValue = "") String maxDate) throws MyException {
		Date startDate = new Date();
		logger.info("queryList begin: " + startDate);

		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("isDeleted", 0);
		reqMap.put("enabled", 1);

		if(StringUtils.isEmpty(sort)){
			reqMap.put("orderByClause","wi.createdate desc");
		} else{
			reqMap.put("orderByClause",sort + " " + order);
		}

		if(!StringUtils.isBlank(title)){
			reqMap.put("_title", title.trim());
		}

		if(!StringUtils.isBlank(author)){
			reqMap.put("_author", author.trim());
		}

		if(!StringUtils.isBlank(minDate) && !StringUtils.isBlank(maxDate)){
			try {
				if(DateUtil.parse(minDate).after(DateUtil.parse(maxDate))){
					reqMap.put("minDate", maxDate + DateUtil.START_DATE_HMS);
					reqMap.put("maxDate", minDate + DateUtil.END_DATE_HMS) ;
				}else{
					reqMap.put("minDate", minDate + DateUtil.START_DATE_HMS);
					reqMap.put("maxDate", maxDate + DateUtil.END_DATE_HMS);
				}
			} catch (ParseException e) {
				logger.error("queryList error: " ,e);
			}
		}	

		PageBounds pageBounds = new PageBounds(page, pageSize);
		List<WenwInfo> list = wenwInfoService.queryByList(reqMap, pageBounds);

		PageList<WenwInfo> pageList = (PageList<WenwInfo>) list;
		Paginator paginator = pageList.getPaginator();

		HashMap<String, Object> indexPages = new HashMap<String, Object>();
		indexPages.put("total", paginator.getTotalCount());	
		indexPages.put("rows", list);

		logger.info("queryList end run(s): " + DateUtil.calLastedTime(startDate));

		return indexPages;
	}

	/**
	 * 
	 * @Title: edit
	 * @Description: 编辑页面
	 * @param @param id
	 * @param @param index_exp
	 * @param @param index_che
	 * @param @return    设定文件
	 * @return ModelAndView    返回类型
	 */
	@RequestMapping(value = "/edit")
	public ModelAndView edit(
			@RequestParam(required = false) String id,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false,defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che) {
		Date startDate = new Date();
		logger.info("edit begin: " + startDate);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_KUNGFU + "wenw_edit");

		if (!StringUtils.isBlank(id)) {
			WenwInfo wenwInfo = wenwInfoService.selectByPrimaryKey(Integer.parseInt(id));
			mv.addObject("wenwInfo", wenwInfo);
		}

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("edit end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	 * @Title: save
	 * @Description: 保存
	 * @param @param wenwInfo
	 * @param @param folPara
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return String    返回类型
	 */
	@RequestMapping(value = "/save",method = RequestMethod.POST)
	public String save(WenwInfo wenwInfo,FolPara folPara,String [] imagename,HttpServletRequest request) throws MyException {
		Date startDate = new Date();
		logger.info("save begin: " + startDate);

		logger.info("reqPara content(before): " + wenwInfo.getContent());

		MstUser mstUser = this.getMySession().getMstUser();

		if (wenwInfo.getId() != null) {
			wenwInfo.setUpdatedate(startDate);
			wenwInfo.setUpdateuser(mstUser.getId());

			wenwInfoService.updateByPrimaryKeySelective(wenwInfo);
		} else {
			wenwInfo.setEnabled(true);
			wenwInfo.setIsdeleted(false);
			wenwInfo.setCreatedate(startDate);
			wenwInfo.setCreateuser(mstUser.getId());
			wenwInfo.setUpdatedate(startDate);

			wenwInfoService.insert(wenwInfo);
		}

		//图片资源信息维护
		try {

			WenwInfo imgWenw = new WenwInfo();
			imgWenw.setUpdatedate(startDate);
			imgWenw.setUpdateuser(mstUser.getId());
			imgWenw.setId(wenwInfo.getId());

			if(imagename != null && imagename.length != 0){
				Map<String, String> resMap = new HashMap<String,String>();
				resMap.put("userId", mstUser.getId().toString());
				resMap.put("ownerId", wenwInfo.getId().toString());
				resMap.put("tableName", "WENW_INFO");
				
								
				Map<String, Object> dataMap = CommonUtils.getResourcesData(request, imagename, resMap,CommonEnum.SYSCODE_REOURCES_TYPE_IMAGE,true);
				
				@SuppressWarnings("unchecked")
				List<Resources> resources = (List<Resources>) dataMap.get("resources");
				String reserved12 = (String) dataMap.get("zipFile");
				
				resourcesService.saveList(resources);

				//默认获取第一次作为常用图：String imagePath = resources.get(0).getRespath() + resources.get(0).getResname();
				//将所有图片获取出来
				String imagePath = "";
				for(Resources resource : resources){
					imagePath += resource.getRespath() + resource.getResname() + ";";
				}

				imgWenw.setCover(imagePath.substring(0 , imagePath.length() - 1));
				imgWenw.setReserved12(reserved12);
				
				wenwInfoService.updateByPrimaryKeySelective(imgWenw);
			}

		} catch (Exception e) {
			logger.error("save error: " ,e);
		}

		StringBuffer sb = new StringBuffer("?");
		sb.append("menuId=" + folPara.getMenuId());
		sb.append("&page=" + folPara.getPage());
		sb.append("&rows=" + folPara.getRows());
		sb.append("&titleFol=" + folPara.getTitleFol());
		sb.append("&authorFol=" + folPara.getAuthorFol());

		sb.append("&minDate=" + folPara.getMinDate());
		sb.append("&maxDate=" + folPara.getMaxDate());
		
		sb.append("&index_exp=" + folPara.getIndex_exp());
		sb.append("&index_che=" + folPara.getIndex_che());

		logger.info("save end run(s):" + DateUtil.calLastedTime(startDate));

		return "redirect:list" + sb.toString();
	}

	/**
	 * 
	 * @Title: isUnique
	 * @Description: 验证属性唯一性
	 * @param @param property 
	 * @param @param id
	 * @param @return    设定文件
	 * @return Boolean    返回类型
	 */
	@RequestMapping(value = "/isUnique",method = RequestMethod.GET)
	@ResponseBody
	public Boolean isUnique(
			@RequestParam(required = true)String property,
			@RequestParam(required = false,defaultValue = "")String id){
		Date startDate = new Date();
		logger.info("isUnique begin: " + startDate);

		boolean flag = false;

		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("enabled", 1);
		reqMap.put("isDeleted", 0);
		reqMap.put("rolNo", property);

		List<WenwInfo> wenws= wenwInfoService.queryByList(reqMap, new PageBounds());

		if(wenws.isEmpty()) flag = true;

		else{
			if(!StringUtils.isBlank(id)){//当为编辑操作时，存在唯一一个相同的名称名，验证通过
				if(wenws.get(0).getId().equals(Integer.valueOf(id))){
					flag = true;
				}
			}
		}
		logger.info("isUnique end run(s): " 
				+ DateUtil.calLastedTime(startDate));

		return flag;
	}


	/**
	 * 
	 * @Title: delList
	 * @Description: 批量删除
	 * @param @param request
	 * @param @param response
	 * @param @param ids
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return boolean    返回类型
	 */
	@RequestMapping("delList")
	@ResponseBody
	public boolean delList(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(required = true) String ids) throws MyException {
		Date startDate = new Date();
		logger.info("delList begin: " + startDate);

		boolean flag = false;

		MstUser mstUser = this.getMySession().getMstUser();

		Map<String, Object> reqMap = new HashMap<String,Object>();
		reqMap.put("ids", ids);
		reqMap.put("updateUser", mstUser.getId());

		try {
			wenwInfoService.delList(reqMap);
			flag = true;
		} catch (Exception e) {
			logger.error("delList error: " ,e);
		}

		logger.info("delList end run(s): " + DateUtil.calLastedTime(startDate));

		return flag;
	}
}
